import { notFound } from "next/navigation";
import { ReaderView } from "@/components/reader/reader-view";
import { getBookById, getBookEntries } from "@/lib/book-catalog";

type ReaderPageProps = {
  params: Promise<{
    bookId: string;
  }>;
  searchParams?: Promise<{
    chapter?: string;
    entry?: string;
    width?: string;
    theme?: string;
    font?: string;
  }>;
};

export default async function ReaderPage({ params, searchParams }: ReaderPageProps) {
  const { bookId } = await params;
  const resolvedSearchParams = searchParams ? await searchParams : undefined;
  const book = await getBookById(bookId);

  if (!book) {
    notFound();
  }

  const entries = getBookEntries(book);
  const rawEntryIndex = Number(resolvedSearchParams?.entry ?? resolvedSearchParams?.chapter ?? "0");
  const chapterIndex =
    Number.isFinite(rawEntryIndex) && rawEntryIndex >= 0 && rawEntryIndex < entries.length
      ? rawEntryIndex
      : 0;

  return (
    <ReaderView
      book={book}
      chapterIndex={chapterIndex}
      initialWidthKey={resolvedSearchParams?.width}
      initialThemeKey={resolvedSearchParams?.theme}
      initialFontKey={resolvedSearchParams?.font}
    />
  );
}
